package com.example.k8s.hello.service.common.config;

import com.example.k8s.hello.common.bean.RestResponse;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice("com.example")
public class ResponseBodyConfig implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object result, MethodParameter methodParameter, MediaType mediaType, Class aClass
            , ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (result instanceof String && result != null) {
            return RestResponse.success(result).toJson();
        }

        if (result instanceof RestResponse || result instanceof byte[]) {
            return result;
        }

        return RestResponse.success(result);
    }
}